//
//  LoginEventProcessor.swift
//  app_rn_frontend
//
//  Created by 鱼涛 on 2017/12/12.
//  Copyright © 2017年 Facebook. All rights reserved.
//

import Foundation
import SwiftHash

class UserDidLoginEventProcessor: EventProcessorProtocol {
    static let instance = UserDidLoginEventProcessor()
    
    private init(){}
    
    func process(params: Dictionary<String, Any>?) throws{
        do{
            guard let userId = params?["userId"] as? Int else{
                throw ProcessError.InvalidParamError
            }
            guard let userName = params?["userName"] as? String else{
                throw ProcessError.InvalidParamError
            }
            guard let accountToken = params?["accountToken"] as? String else{
                throw ProcessError.InvalidParamError
            }
            let userIdMD5 = MD5("\(userId)").uppercased()
            
            let fm = FileManager.default
            //      let urlForDocument = fm.urls(for: .documentDirectory, in:.userDomainMask)[0] as URL
            let urlForDocument = fm.containerURL(forSecurityApplicationGroupIdentifier: "group.missle-chat")!
            
            let urlForUser = urlForDocument.appendingPathComponent(userIdMD5, isDirectory: true)
            try fm.createDirectory(at: urlForUser, withIntermediateDirectories: true, attributes: nil)
            
            let urlForUserAvatar = urlForUser.appendingPathComponent("avatar", isDirectory: true)
            try fm.createDirectory(at: urlForUserAvatar, withIntermediateDirectories: true, attributes: nil)
            
            
            //      ConfigHelper.instance.set(key: ConfigKey.userId, value: "\(userId)")
            //      ConfigHelper.instance.set(key: ConfigKey.userName, value: userName)
            //      ConfigHelper.instance.set(key: ConfigKey.accountToken, value: accountToken)
            //      ConfigHelper.instance.set(key: ConfigKey.distributorAccount, value: distributorAccount)
            //      ConfigHelper.instance.set(key: ConfigKey.userKey, value: userKey)
            
            AppStatusManager.instance.urlForUser = urlForUser
            AppStatusManager.instance.urlForUserAvatar = urlForUserAvatar
            AppStatusManager.instance.accountToken = accountToken
            AppStatusManager.instance.urlForUserDB = urlForUser.appendingPathComponent("chat.db", isDirectory: false)
            AppStatusManager.instance.userLoginStatus = (true, userId, userName);
            CloudPushSDK.bindAccount(String(userId)) { _ in }
            try SQLiteHelper.buildUserDatabase(urlForUser: urlForUser, dbName: "chat.db")
        }catch{
            print(error)
            throw error
        }
        
    }
}
